#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under GPL v2 or later at your option
# Copyright 2007, İsmail Dönmez

import sys
import os
import tempfile
import getopt
import subprocess
import time
import urllib2_file
import urllib2
from mechanize import Browser
from BeautifulSoup import BeautifulSoup

def grabQuota(username=None,password=None):
    br = Browser()
    br.addheaders = [("User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)")]

    # Download CAPTCHA image
    imageData = br.open("http://adslkota.ttnet.net.tr/adslkota/jcaptcha").read(4096*10)
    tmpFile = tempfile.mkstemp()[1];
    imageFile = open(tmpFile, "w")
    imageFile.write(imageData)
    imageFile.close()

    # Use captchakiller.com to solve captcha
    data = {
        'method' : 'upload_captcha',
        'api_key' : 'EE05855B-391B-B86A-6DAC-B393EB08325D',
        'file' : open(tmpFile),
        'expire' : '300',
        'rights' : 'true'
        }
    success = False

    while not success:
        result=urllib2.urlopen('http://www.captchakiller.com/api.php', data).read().strip()
        if result.startswith("FAILURE"):
            print "Captcha detection failed : %s" % result.split(':')[-1]
            return
        elif result.startswith("SUCCESS"):
            success = True
            id = result.split('=')[-1]

    # Remove temporary file
    os.unlink(tmpFile)

    data = {
        'method' : 'get_result',
        'api_key' : 'EE05855B-391B-B86A-6DAC-B393EB08325D',
        'captcha_id' : id
        }
    solved = False

    while not solved:
        result = urllib2.urlopen('http://www.captchakiller.com/api.php', data).read().strip()
        if result.startswith("WAIT"):
            print "Sleeping 10 seconds..."
            time.sleep(10)
        elif result.startswith("FAILURE"):
            print "Error occurred: %s" % result
            return
        elif result.startswith("SUCCESS"):
            solved = True
            captcha = result.split('=')[-1].replace('"','')

    br.open("http://adslkota.ttnet.net.tr/adslkota/login.jsp")
    br.select_form(nr=0)
    br["userName"]=username
    br["password"]=password
    br["captchaResponse"]=captcha
    br.submit()

    br.open("http://adslkota.ttnet.net.tr/adslkota/confirmAgreement.do","dispatch=agree")
    response = br.open("http://adslkota.ttnet.net.tr/adslkota/viewTransfer.do","dispatch=entry")

    soup = BeautifulSoup(response.read(),fromEncoding="windows-1254")
    quotaTable = soup.find('table',align='center')

    i=1
    for data in quotaTable.findAll('td'):
        print data.contents[0],
        if i % 4 == 0:
            print
        i += 1

def showHelp():
    print 'Usage: kota.py -u username -p password'
    sys.exit(1)

if __name__ == "__main__":
    username = None
    password = None

    try:
        opts, args = getopt.getopt(sys.argv[1:],"u:p:h",["username=","password=","help"])
        for opt, arg in opts:
            if opt in ("-h","--help"):
                showHelp()
            elif opt in ("-u","--username"):
                username = arg
            elif opt in ("-p","--password"):
                password = arg

        if username and password:
            grabQuota(username,password)
        else:
            showHelp()
    except getopt.GetoptError:
        showHelp()
        sys.exit(1)
